<script setup lang="ts">
import { onMounted, ref, watch, nextTick } from 'vue'
import { MapComponentProps } from '../MapComponent'
import 'ol/ol.css'
import { Map, View } from 'ol'
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
import OpenlayersMapStore from './utils/OpenlayersMapStore'
import { MapContainerType } from '../Constant/MapContainerType'

const props = defineProps(MapComponentProps)
const emits = defineEmits(['init'])

const mapContainer = ref('')
let map: Map | undefined

// 组件挂载并且可见，初始化地图
onMounted(() => {
    if (props.visible && props.show) {
        initMap()
    }
})

// 组件挂载并且可见，初始化地图
watch([() => props.visible, () => props.show], () => {
    // 地图显示并且没有初始化
    if (props.visible && props.show && !map) {
        initMap()
    } else if (!props.visible) {
        destroyMap()
    }
})

/**
 * 初始化地图
 */
const initMap = () => {
    nextTick(() => {
        _initMap()
    })
}

/**
 * 销毁地图
 */
const destroyMap = () => {
    console.log('销毁地图')
    map && map.dispose && map.dispose()
    map = undefined
}

/**
 * 初始化地图
 */
const _initMap = () => {
    console.log("ol initMap")
    if (map) {
        return
    }
    // 初始化视图对象
    const view = new View({
        // center: fromLonLat([115.97852713758685, 30.560407944979296], 'EPSG:3857'),
        center: [115.97852713758685, 30.560407944979296], // 地图中心坐标
        zoom: 4,
        projection: 'EPSG:4326',// 坐标系类型
    })

    // 创建ArcGIS World Street Map图层
    const arcGISLayer = new TileLayer({
        source: new XYZ({
            // url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',
            // url: 'https://gac-geo.googlecnapps.cn/maps/vt?lyrs=s&x={x}&y={y}&z={z}',
            url: 'http://t{0-7}.tianditu.com/DataServer?T=img_c&tk=4267820f43926eaf808d61dc07269beb&x={x}&y={y}&l={z}',
            projection: 'EPSG:4326',// 坐标系类型
        }),
    })

    // 初始化地图对象
    map = new Map({
        controls: [], // 地图控件
        target: mapContainer.value,
        layers: [arcGISLayer],
        view: view,
    })
    // @ts-ignore
    window.openlayersMap = map;
    OpenlayersMapStore.setMap(map)
    emits('init', MapContainerType.OpenlayersMap)

    // addVectorTile(map)
}


</script>

<template>
    <div v-if="visible" v-show="show" class="openlayers-map" ref="mapContainer"></div>
</template>

<style scoped lang="scss">
@import './css/OpenlayersMap.scss';
</style>
